package com.situ.mall.service.impl;

import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.Order;
import com.situ.mall.pojo.OrderItem;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.pojo.vo.OrderVO;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public boolean add(Order order) {
        //现在这个order对象里面已经有userId、shippingId、paymentType、
        //使用雪花算法生成order的主键
        long id = snowFlake.nextId();
        order.setOrderNo(id);

        // 整个订单总金额
        BigDecimal payment = BigDecimal.valueOf(0.0);
        //这个用户购物车里面勾选的要结算的商品
        List<CartVO> cartVOList = cartMapper.selectByUserIdAndChecked(order.getUserId());
        for (CartVO cartVO : cartVOList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(id);
            orderItem.setUserId(order.getUserId());
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImage(cartVO.getProductMainImage());
            orderItem.setCurrentUnitPrice(cartVO.getProductPrice());
            orderItem.setQuantity(cartVO.getQuantity());

            //计算当前商品数量*价格
            BigDecimal productPrice = cartVO.getProductPrice();
            BigDecimal quantity = BigDecimal.valueOf(cartVO.getQuantity());
            BigDecimal totalPrice = productPrice.multiply(quantity);
            orderItem.setTotalPrice(totalPrice);
            payment = payment.add(totalPrice);

            orderItemMapper.insertSelective(orderItem);

            //删除购物车里面的当前商品
            cartMapper.deleteByPrimaryKey(cartVO.getId());

        }

        order.setPayment(payment);
        int count = orderMapper.insertSelective(order);
        return count == 1 ;
    }

    @Override
    public List<OrderVO> selectByUserId(Integer id) {
        return orderMapper.selectByUserId(id);
    }
}
